
import React, { Component, useState, useEffect } from 'react';
import {View, StyleSheet,Text,Button, ScrollView,RefreshControl} from 'react-native';
import IndexModel, { getCourseDatas } from "../models/Index";
import IndexSwiper from '../components/IndexSwiper'
import MainTitle from '../components/MainTitle';


const Home = (props) => {
    
    const wait = (timeout) => {
        return new Promise(resolve => {
          setTimeout(resolve, timeout);
        });
      }
    const indexModel = new IndexModel();
    
    const [swiperData, setSwiperData] = useState([]);
    //const [fieldData, setFieldData] = useState([]);
    //const [courseData, setCourseData] = useState([]);
    //const [recomCourseData, setRecomCourseData] = useState([]);
    const [isRefreshing, setIsRefreshing] = useState(false);

    const getCoursesDatas = () => { 
        console.log("getdata");
        indexModel.getCourseDatas().then((res) => {
            const data = res.result;
            setSwiperData(data.swipers);
            // setFieldData(data.fields);
            // setCourseData(data.courses);
            // setRecomCourseData(data.recomCourses);
        })
    }

    useEffect(() => {
        getCoursesDatas();
    }, []);

    const {navigation} = props

    //下拉刷新
    const renderRefreshControl = (options) =>{
        const {isRefreshing,title} = options
        return (
            <RefreshControl
                refreshing={isRefreshing}
                onRefresh={onRefresh}
                tintColor="#666"
                title={title}
                titleColor="#666"
            />  
        )
    }
    const onRefresh = React.useCallback(() => {
        setIsRefreshing(true);
        getCoursesDatas();
        wait(2000).then(() => setIsRefreshing(false));
      }, []);

    return (
        <ScrollView
            automaticallyAdjustContentInsets={false}
            showVerticalScrollIndicator={false}
            refreshControl={
                renderRefreshControl({isRefreshing,title:'正在加载中'})
            }
        >
            <Button
                title="Go to Detail"
                onPress={() => navigation.navigate('Detail')}
            />  
            <IndexSwiper 
                swiperData={swiperData}
                navigation={navigation}
            />
            <MainTitle
                title="推荐课程"
            />
            <Button
                title="Go to video"
                onPress={() => navigation.navigate('Video')}
            />  
        </ScrollView>
    );
    
}

export default Home;
